package cn.wowjoy.pda.android_pharmacy.ui.activity.hospital.take;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;

import cn.wowjoy.pda.android_pharmacy.R;
import cn.wowjoy.pda.android_pharmacy.common.core.BaseActivity;
import cn.wowjoy.pda.android_pharmacy.common.utils.Contants;
import cn.wowjoy.pda.android_pharmacy.common.utils.NetWorkUtils;
import cn.wowjoy.pda.android_pharmacy.common.utils.PreferenceManager;
import cn.wowjoy.pda.android_pharmacy.common.widget.CreateDialog;
import cn.wowjoy.pda.android_pharmacy.common.widget.MDialog;
import cn.wowjoy.pda.android_pharmacy.common.widget.MyToast;
import cn.wowjoy.pda.android_pharmacy.databinding.ActivityInHospitalTakeProgressBinding;
import cn.wowjoy.pda.android_pharmacy.model.xmlEntity.inHospitalPatientInfo.InHospitalPatientBeen;
import cn.wowjoy.pda.android_pharmacy.mvvm.presenter.InHospitalTakeProgressPresenter;
import cn.wowjoy.pda.android_pharmacy.mvvm.vm.InHospitalTakeProgressViewModel;

public class InHospitalTakeProgressActivity extends BaseActivity<ActivityInHospitalTakeProgressBinding,InHospitalTakeProgressViewModel,InHospitalTakeProgressPresenter> implements  InHospitalTakeProgressPresenter.OnSubmitResult {

    private MDialog failSubmit;
    private MDialog mMDialog;
    private float countAlready = 0;
    private InHospitalPatientBeen remove;
    //当次药单 种类总数量
    private  float TOTAL_NUM = Integer.parseInt(PreferenceManager.getInstance().getHospitalTakeProgressTotal());
    //设置缓存柜是否成功
    private boolean isSetCache = false;
    //是否取完药
    private boolean isGetAll = false;


    //PDA扫码广播
    private ScanReceiverHospitalTake mScanReceiver;
    private IntentFilter intentFilter;

    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setViweModel(viewModel);
        binding.setPresenter(presenter);
        binding.medicineIdScanGet.setText(presenter.DJJLID);
//        presenter.registeOnScanResultListener(this);
        presenter.registeOnSubmitResultListener(this);
        binding.scanGetTitle.titleTextTv.setText("扫码取药");
        binding.scanGetTitle.titleBackLl.setVisibility(View.VISIBLE);
        binding.scanGetTitle.titleBackLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                if (viewModel.mMoveBaens.size() != 0) {
                    viewModel.mMoveBaens.add(0,remove);
                }
                if (TOTAL_NUM - countAlready == 1) {
                    viewModel.mMoveBaens.add(0,remove);
                }
                intent.putExtra("currently", viewModel.mMoveBaens);
                setResult(Contants.REQUEST_BACK_CODE, intent);
                finish();
            }
        });
        binding.scanGetTitle.titleBackTv.setText("取药单详情");
        binding.btDoorTakeProgressSureSuccess.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO:整个单子完成，跳转到Index     还要判断是否是2人同时操作同一个订单 先后完成？？
                if(NetWorkUtils.isWifi(InHospitalTakeProgressActivity.this)){
                    presenter.queryKForZJ();
                }else{
                    CreateDialog.failDialog3(InHospitalTakeProgressActivity.this,"错误","当前网络不可用，请检查你的网络设置");
                }
            }
        });

        //TODO:进度条更新   分子什么时候加一
        ifBack();
        updateFirstUI();
        //TODO:PDA扫码广播的接收跳转
        mScanReceiver = new ScanReceiverHospitalTake();
        intentFilter = new IntentFilter();
        intentFilter.addAction(Contants.WOW_NEW_ADD);

//        binding.imgv123.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                presenter.update("0",PreferenceManager.getInstance().getLUserId());
//                Intent intent = new Intent(InHospitalTakeProgressActivity.this, InHospitalTakeProgressDetailActivity.class);
//                intent.putExtra("topRemove",remove);
//                startActivityForResult(intent, Contants.REQUEST_CODE);
//            }
//        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case Contants.REQUEST_CODE:
                switch (resultCode){
                    case Contants.RESULT_SUCCESS_CODE:
                        //进度+1 ，界面展现集合中的第一个
                        if (countAlready < TOTAL_NUM){
                            countAlready++;
                        }

                        if(countAlready == TOTAL_NUM){
                            //扫码完成
//                            binding.scanGetTitle.titleTextTv.setText("放入缓存柜");
                            binding.llScanGetStart.setVisibility(View.GONE);
                            binding.rlScanGetEnd.setVisibility(View.VISIBLE);
                            binding.rlVoice.setVisibility(View.VISIBLE);
                            binding.scanGetTitle.titleBackLl.setVisibility(View.GONE);
                            binding.tvProgressScanGet.setText((int)countAlready + "/" + (int)TOTAL_NUM);
                            binding.progressScanGet.setProgress(100);
                        }
                        updateFirstUI();
                        break;
                    case Contants.RESULT_FAIL_CODE:
                        //back键 界面不做更新

                        break;
                }
                break;
        }
    }
    private void ifBack(){
        //说明是0/12 Back回去的
//        if(viewModel.FirstTotal.size() == TOTAL_NUM){
//            binding.tvProgressScanGet.setText(countAlready+"/"+ TOTAL_NUM);
//        }
        //说明是中途取到2/12 回去的
        if(viewModel.FirstTotal.size() < TOTAL_NUM){
            countAlready=TOTAL_NUM - viewModel.FirstTotal.size();
        }
    }
    //TODO:界面药品信息的更新   库位和处方号的更新？？
    private void updateFirstUI() {
        binding.tvProgressScanGet.setText((int)countAlready+"/"+ (int)TOTAL_NUM);
        if(viewModel.mMoveBaens.size() > 0){
            remove = viewModel.remove();
            if( null != remove.getKFWZMC() && remove.getKFWZMC().length()>6){
                binding.locatorScanGet.setText(remove.getKFWZMC().substring(0,7));  //库位
            }else{
                binding.locatorScanGet.setText(remove.getKFWZMC());  //库位
            }
            if(null != remove.getSFGWPB() && !"".equals(remove.getSFGWPB())){
                if(Integer.parseInt(remove.getSFGWPB()) == 1){
                    binding.medicineNameScanGet.setTextColor(getResources().getColor(R.color.red));
                }else {
                    binding.medicineNameScanGet.setTextColor(getResources().getColor(R.color.text_undanger));
                }
            }

            binding.medicineNameScanGet.setText(remove.getZZYPMC()+"  "+remove.getZZYPGG());
            binding.numScanGet.setText(remove.getCFYPSL()+" "+remove.getYPBZDW());
            binding.placeScanGet.setText(remove.getYPCDMC());
            binding.progressScanGet.setProgress((int)((countAlready /TOTAL_NUM)*100));
        }
        if(countAlready == TOTAL_NUM){
            //8/8 BACK回去的
            binding.llScanGetStart.setVisibility(View.GONE);
            binding.rlScanGetEnd.setVisibility(View.VISIBLE);
            binding.rlVoice.setVisibility(View.VISIBLE);
            binding.scanGetTitle.titleBackLl.setVisibility(View.GONE);
            binding.progressScanGet.setProgress(100);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_in_hospital_take_progress;
    }

    @Override
    protected Class<InHospitalTakeProgressPresenter> getPresenterClass() {
        return InHospitalTakeProgressPresenter.class;
    }

    @Override
    protected Class<InHospitalTakeProgressViewModel> getViewModelClass() {
        return InHospitalTakeProgressViewModel.class;
    }
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mScanReceiver, intentFilter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(mScanReceiver);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        CreateDialog.dismiss(InHospitalTakeProgressActivity.this);
        if(null != mMDialog){
            mMDialog.cancel();
        }
        if(null != failSubmit){
            failSubmit.cancel();
        }
    }
    @Override
    public void onBackPressed() {
        //药单未完成  BACK键返回  每次要把当前展示的加到集合中
        Intent intent=new Intent();
        if(viewModel.mMoveBaens.size() !=0 ){
            viewModel.mMoveBaens.add(0,remove);
        }
        if(TOTAL_NUM - countAlready == 1){
            viewModel.mMoveBaens.add(0,remove);
        }
        intent.putExtra("currently",viewModel.mMoveBaens);
        setResult(Contants.REQUEST_BACK_CODE,intent);
        super.onBackPressed();
    }

    //更新整个单子成功
    @Override
    public void submitSuccess() {
        new MyToast(InHospitalTakeProgressActivity.this).showinfo("取药成功");
        startActivity(new Intent(InHospitalTakeProgressActivity.this, InHospitalTakeIndexActivity.class));
        finish();
    }
    //更新整个单子失败
    @Override
    public void submitFail(String errMsg) {
        //单子更新异常
//        new MyToast(InHospitalTakeProgressActivity.this).showinfo(errMsg);
         failSubmit = CreateDialog.failSubmit(InHospitalTakeProgressActivity.this, "无法进行取药", errMsg, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(InHospitalTakeProgressActivity.this, InHospitalTakeIndexActivity.class));
                finish();
            }
        });
    }
    //TODO:接收PDA扫码广播，准备跳转
    class ScanReceiverHospitalTake extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()){
                case Contants.WOW_NEW_ADD:
                    String stringExtra = intent.getStringExtra(Contants.WOW_NEW_KEY);
//                   new MyToast(InHospitalTakeProgressActivity.this).showinfo("扫到的是: "+stringExtra);
//                    Log.e("onReceive1: ", remove.toString());
                    if( binding.rlScanGetEnd.getVisibility() == View.GONE){
                       if(stringExtra.length() == 20){
                            //监管码 前7位
                            if(presenter.confimYPJGBM(stringExtra.substring(0,7))){
                                Intent intent2 = new Intent(InHospitalTakeProgressActivity.this, InHospitalTakeProgressDetailActivity.class);
                                intent2.putExtra("topRemove",remove);
                                startActivityForResult(intent2, Contants.REQUEST_CODE);
                            }else{
                                mMDialog= CreateDialog.failDialog(InHospitalTakeProgressActivity.this);
                            }
                            break;
                        }else if(stringExtra.length() == 7){
                            //药监码
                            if(presenter.confimKFWZMC(stringExtra)){
                                Intent intent2 = new Intent(InHospitalTakeProgressActivity.this, InHospitalTakeProgressDetailActivity.class);
                                intent2.putExtra("topRemove",remove);
                                startActivityForResult(intent2, Contants.REQUEST_CODE);
                            }else{
                                mMDialog= CreateDialog.failDialog(InHospitalTakeProgressActivity.this);
                            }
                            break;
                        }else {
                               //药品码
                               //扫码后进行对比，true跳转，false弹框提示
                               if(presenter.confimYPSPBM(stringExtra)){
                                   Intent intent2 = new Intent(InHospitalTakeProgressActivity.this, InHospitalTakeProgressDetailActivity.class);
                                   intent2.putExtra("topRemove",remove);
                                   startActivityForResult(intent2, Contants.REQUEST_CODE);
                               }else{
                                   mMDialog= CreateDialog.failDialog(InHospitalTakeProgressActivity.this);
                               }
                               break;
                        }
                    }
            }
        }
    }
}
